//
//  KzTableView.swift
//  Trans
//
//  Created by zcj on 2024/11/21.
//

import SwiftUI
class TableHeader{
    //存放identify和实际可以看到的表头
    var dic : Dictionary<String,String> = Dictionary()
    //存放identify的排序
    var arr :[String] = Array()
}
protocol KzTableViewDelegate{
    func gridView(identify:String,data:Any) -> AnyView;//使用AnyView 是正确的，不能是some View 或者 Any View。通过identify和 row 来返回相应的View
}

//模仿objecive-c 的tableview来实现相关功能
struct KzTableView<TDelegate:KzTableViewDelegate>: View {
    var delegate:TDelegate
    var size:CGSize = NSMakeSize(500, 350)
    
    //表头
    @Binding var tableColumns :Array<KzTableColumn>
    @Binding var dataSource:Array<Any>
    
    var body: some View {
        if dataSource.count == 0{
            Text("no data")
        }else{
            VStack {
                HStack{
                    ForEach(tableColumns.indices, id:\.self){ index in
                        Text(tableColumns[index].title).multilineTextAlignment(.center)
                            .frame(width: columnWid(tb: tableColumns[index]),height: 20)
                        Divider().padding(.vertical,0).background(kcolors.lineColor).frame(height:20 )
                    }
                }
                ForEach(0..<dataSource.count, id: \.self) { index in
                    let data = dataSource[index]
                    HStack{
                        ForEach(tableColumns.indices, id:\.self){ tbindex in
                            delegate.gridView(identify: tableColumns[tbindex].identity,data: data).frame(width: columnWid(tb: tableColumns[tbindex]),height: 20)
                            Divider().padding(.vertical,0).background(kcolors.lineColor).frame(height:20 )
                        }
                        
                    }
                
                    Divider().padding(.horizontal,0).background(kcolors.lineColor)
                }
            }.frame(width: size.width,height: size.height,alignment: .top)
        }
    }
    
    func columnWid(tb:KzTableColumn) -> CGFloat{
        var width = tb.width
        if tb.ifPercent{
            width = self.size.width * tb.percent
        }
        return width
    }
}

//#Preview {
//    KzTableView<dataSingle: dataInterface>(colNums: .constant(0), rowNums: .constant(0),  tb: TableHeader())
//}
